package com.apes.scm.masterdata.stock.service;

import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.scm.masterdata.area.model.Area;
import com.apes.scm.masterdata.area.repository.AreaRepository;
import com.apes.scm.masterdata.stock.model.PhyDepot;
import com.apes.scm.masterdata.stock.repository.PhyDepotRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 功能：物理仓库
 *
 * @author HuJianlin
 * @create 2018-03-14 9:45
 */
@Service("phyDepotService")
public class PhyDepotService extends DomainService {
    @Autowired
    public PhyDepotRepository phyDepotRepository;

    @Autowired
    public AreaRepository areaRepository;
    
    public PhyDepot save(SimpleRequest request) {
        PhyDepot phyDepot = request.getO(PhyDepot.class);

        // 区县
        Area county = phyDepot.getCounty();
        // 城市
        Area city = areaRepository.findOne(county.getParent()) ;
        // 省份
        Area province = areaRepository.findOne(city.getParent()) ;

        phyDepot.setCounty(county);
        phyDepot.setCity(city);
        phyDepot.setProvince(province);

        return phyDepotRepository.saveAndFlush(phyDepot);
    }

    public PhyDepot update(SimpleRequest request) {
        return save(request);
    }


    public String delete(SimpleRequest request) {
        PhyDepot phyDepot = request.getO(PhyDepot.class);
        phyDepotRepository.delete(phyDepot);
        return "删除成功";
    }

    /**
     * 功能：下拉模糊查询使用
     * @param request
     * @return
     */
    public Page<PhyDepot> find(SimpleRequest request) {
        String value = request.get("key");
        long id;
        try {
            id = Long.valueOf(value);
        } catch (Exception e){
            id = -1;
        }
        return phyDepotRepository.find(value, value, PageRequest.of(request.get("page"), request.get("size")) );
    }
}
